function tcpServer(){
    var _tcpServer = chrome.sockets.tcpServer;
    this.option = {},
    this.socketId = 0,

    this.create = function(callback){
        _tcpServer.create(this.option, function(socketInfo){
            this.socketId = socketInfo.socketId;
            callback();
        }.bind(this));
    }.bind(this),

    this.update = function(){
        _tcpServer.update(this.socketId, newSocketOption, callback);
    }.bind(this),

    this.pause = function(isPaused, callback){
        _tcpServer.setPaused(this.socketId, isPaused, callback);
    }.bind(this),

    this.disconnect = function(callback){
        _tcpServer.disconnect(this.socketId, callback);
    }.bind(this),

    this.close = function(callback){
        _tcpServer.close(this.socketId, callback);
    }.bind(this),

    this.init = function(callback){
        this.create(callback);
    }.bind(this)

    this.listen = function(address, port, callback){
        _tcpServer.listen(this.socketId, address, port, function(code){
            if(code<0){
                this.error(code);
                return false;
            }
            else{
                _tcpServer.onAccept.addListener(function(info){
                    if(info.socketId==this.socketId){
                        this.accept(info);
                    }
                }.bind(this));
                _tcpServer.onAcceptError.addListener(function(info){
                    if(info.socketId==this.socketId){
                        this.error(info.resultCode);
                    }
                }.bind(this));
                callback();
            }
        }.bind(this));
    }.bind(this),

    this.error = function(code){
        console.log('An error occurred with code '+code);
    },

    this.accept = function(info){
        console.log('New connection.');
    }

    this.getInfo = function(callback){
        _tcpServer.getInfo(this.socketId, callback);
    }.bind(this),

    this.getSockets = function(callback){
        _tcpServer.getSockets (callback);
    }.bind(this)
}

var tcpServerSocket = new tcpServer();
var routerProxy = undefined;

tcpServerSocket.option = {
    persistent: true
};

tcpServerSocket.accept = handleAccept.bind(tcpServerSocket);
tcpServerSocket.init(function(){
    tcpServerSocket.listen('127.0.0.1', 9798, function(){
        console.log('Listening 127.0.0.1:9798...');
    });
});

function handleAccept(info){
    if(info.socketId==this.socketId){
        var _tcp = chrome.sockets.tcp;
        var tcpSocket = new tcp();
        tcpSocket.socketId = info.clientSocketId;
        tcpSocket.keepAlive(true, 5, function(){
            _tcp.onReceive.addListener(function(info){
                if(info.socketId==tcpSocket.socketId){
                    tcpSocket.receive(info);
                }
            });
            _tcp.onReceiveError.addListener(function(info){
                if(info.socketId==tcpSocket.socketId){
                    tcpSocket.error(info.resultCode);
                }
            });
            tcpSocket.receive = handleRequest.bind(tcpSocket);
            tcpSocket.pause(false, function(){
                console.log('Receiving data...');
            });
        });
    }
}

function handleRequest(info){
    var header = ab2str(info.data);
    var gerreq = header.split("\n")[0];
    var getpath = gerreq.split(" ")[1];
    var path = getpath.split("?")[0];
    var parm = getpath.split("?")[1];
    var parms = {};
    if (parm !== undefined) {
        var ps = parm.split("&");
        for (var i = 0; i < ps.length; i++) {
            var pair = ps[i].split("=");
            parms[pair[0]] = pair[1];
        }
    }
    
    routerProxy.postMessage({request:{'path':path,'parms':parms}});
    var response = "success";
    console.log(response);
    response = str2ab(response);

    this.send(response, function(){
        console.log('Sent.');
        this.close(function(){
            console.log('Closed.');
        })
    }.bind(this));
}

function str2ab(str){
    var buf = new ArrayBuffer(str.length);
    bufView = new Uint8Array(buf);
    for(var i=0; i<str.length; i++){
        bufView[i] = str.charCodeAt(i);
    }
    return buf;
}

function ab2str(buf){
    return String.fromCharCode.apply(null, new Uint8Array(buf));
}

chrome.runtime.onConnect.addListener(function(port){
    console.assert(port.name === "router_proxy")
    port.onMessage.addListener(function(msg){
        if (msg.method === "init") {
            console.log("init")
            routerProxy = port;
            return;
        }
        if (msg.method === "close") {
            console.log("close")
            tcpServerSocket.disconnect(function() {
                tcpServerSocket.close(function() {
                    routerProxy.postMessage({request:{'path':"/system/close",'parms':{}}});
                });
            });
            return;
        }
    });
});

